- Notifications
You must be signed in to change notification settings - Fork 5.8k
/
Copy path306. Additive Number.go
47 lines (43 loc) · 1.02 KB
/
306. Additive Number.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package leetcode
import (
"strconv"
"strings"
)
// This function controls various combinations as starting points
funcisAdditiveNumber(numstring) bool {
iflen(num) <3 {
returnfalse
}
forfirstEnd:=0; firstEnd<len(num)/2; firstEnd++ {
ifnum[0] =='0'&&firstEnd>0 {
break
}
first, _:=strconv.Atoi(num[:firstEnd+1])
forsecondEnd:=firstEnd+1; max(firstEnd, secondEnd-firstEnd) <=len(num)-secondEnd; secondEnd++ {
ifnum[firstEnd+1] =='0'&&secondEnd-firstEnd>1 {
break
}
second, _:=strconv.Atoi(num[firstEnd+1 : secondEnd+1])
ifrecursiveCheck(num, first, second, secondEnd+1) {
returntrue
}
}
}
returnfalse
}
funcmax(aint, bint) int {
ifa>b {
returna
}
returnb
}
// Propagate for rest of the string
funcrecursiveCheck(numstring, x1int, x2int, leftint) bool {
ifleft==len(num) {
returntrue
}
ifstrings.HasPrefix(num[left:], strconv.Itoa(x1+x2)) {
returnrecursiveCheck(num, x2, x1+x2, left+len(strconv.Itoa(x1+x2)))
}
returnfalse
}